// components/playBill/playBill.js
// import { pinyin } from 'pinyin-pro';

Component({
    /**
     * 组件的属性列表
     */
    properties: {
      workerName:{
        type: String,
        observer: function(newVal, oldVal, changedPath) {
          console.log('监听子组件workerName', newVal, oldVal, changedPath)
          // 属性被改变时执行的函数（可选），也可以写成在methods段中定义的方法名字符串, 如：'_propertyChange'
          let that = this
          let trans = this.data.staffObj
          trans.name = newVal
          let workerPic = `cloud://cloud1-5gc90rkv0c4a396c.636c-cloud1-5gc90rkv0c4a396c-1310135976/worker/${newVal}.jpg`
          let nullPic = 'cloud://serverace-4g404vuyeda33e17.7365-serverace-4g404vuyeda33e17-1308232720/zcode.png'
          wx.getImageInfo({
            src: workerPic,
            success(res) {
              console.log('员工图片生成Path', res.path)
              that.setData({
                staffObj: trans,
                workerLogo: res.path,
                showCreateBtn: true
              }) 
            },
            fail(cres){  console.log('员工图片生成调用失败', cres) 
                wx.getImageInfo({
                  src: nullPic,
                  success(res) {
                    that.setData({
                      staffObj: trans,
                      workerLogo: res.path
                    })
                  } }) } })
              }
      },
      workerId:{
        type: String,
        observer: function(newVal, oldVal, changedPath) {
          console.log('监听子组件workerId', newVal, oldVal, changedPath)
          // 属性被改变时执行的函数（可选），也可以写成在methods段中定义的方法名字符串, 如：'_propertyChange'
          let trans = this.data.staffObj
          trans.id = newVal
          this.setData({
            staffObj: trans
          })
        }
      },
      imageFromPath:{
        type: String,
      },
      area:{
        type: String,
        observer: function(newVal, oldVal, changedPath) {
          console.log('监听子Area', newVal, oldVal, changedPath)       
          this.setData({
            area: newVal
          })
        }
      }
    },

    /**
     * 组件的初始数据
     */
    data: {
        evalatImage:'',
        bgBanner:'',  // canvas背景pic
        workerLogo: '', // canvas人像pic
        imagePath:"", // 最终呈现的pic 
        maskHidden:false,
        qrcode_image:'',
        canvasImage: '',
        staffObj:{}, // 员工信息
        showCreateBtn: true, // 显示生成btn
        jpgurl : 'cloud://serverace-4g404vuyeda33e17.7365-serverace-4g404vuyeda33e17-1308232720/gdbg.jpg',
        inCanvasLoading: false,
        area: '江门'
    },

    lifetimes: {
        attached: function() {
          // 在组件实例进入页面节点树时执行
          let that = this;
          let jpgurl = 'cloud://serverace-4g404vuyeda33e17.7365-serverace-4g404vuyeda33e17-1308232720/gdbg.jpg' // https://pan.gcable.tv/seafhttp/files/7c6f2c32-250a-4998-8fc3-c02970de773d/share_bg.jpg
          console.log('attached', this.data.workerName)
          let workerPic = `cloud://serverace-4g404vuyeda33e17.7365-serverace-4g404vuyeda33e17-1308232720/worker/${this.data.workerName}.jpg`
          let defaultPic = ''
          wx.getImageInfo({
            src: jpgurl,
            success(res) {
              console.log("海报底部背景:" + res.path);
              that.setData({
                bgBanner: res.path
              },()=>{
                // setTimeout(()=>{  // this.bannerCreate()
                // },3100)
              })
            },
          })
        //   let qr_image = await that.create_qrcode_image({ worker:'周纪峰', uuid:'zhoujifeng-总部中-装维工程师' })
        //   wx.getImageInfo({
        //     src: qr_image,
        //     success:(res)=> {       
        //       this.setData({
        //         qrcode_image: res.path
        //       })  }
        //   }) 
        },
        detached: function() {
        },
      },

    /**
     * 组件的方法列表
     */
    methods: {
  //新版点击生成海报
  async bannerCreate(){
    console.log('生成海报地区/员工',this.data.area, this.data.staffObj)
    this.setData({ inCanvasLoading: true })
    // this.creatingBanner() // 提前获取
    // 非员工扫码进来专属页面写法，即时获取
    let qr_image = await this.create_qrcode_image({ 
      worker:this.data.staffObj.name, 
      uuid: this.data.staffObj.id   }) // 转为'拼音'-'区域'-'工种' 称号(待定)
    wx.getImageInfo({
      src: qr_image,
      success:(res)=> {
        console.log("X二维码:" + res.path);
        this.setData({
          qrcode_image: res.path
        },()=>{
          let wordslist = this.data.staffObj.id.split('-')[2]?this.data.staffObj.id.split('-')[2]:this.data.staffObj.id
          console.log("wordslist:" + wordslist );
          this.creatingBanner({ worker: this.data.staffObj.name , type: wordslist })
        }) 
      }
    }) 

  },
  creatingBanner(data){
    const query = wx.createSelectorQuery()
    query.select('#xCanvas')
    .fields({
        node: true, size: true  })
    .exec((res)=>{
        const { node } = res[0]
        if (!node) return
        /* 获取 canvas 实例 */
        const context = node.getContext('2d')     
        const {
          windowHeight,
          windowWidth,
          pixelRatio
      } = wx.getSystemInfoSync() /* 动态获取设备的宽和高  */
        const dpr = pixelRatio // 获取dpi 动态缩放
        node.width = res[0].width * dpr 
        node.height = res[0].height * dpr 
        context.scale(dpr, dpr)
        context.fillStyle = 'lightcyan'
        const image = node.createImage()
        wx.getImageInfo({src: this.data.jpgurl }).then( res=>{
          const {
            width,   /* 宽度 */
            height,  
            path     /* 临时路径 */
          } = res
          console.log('画布长宽', node.width, node.height, '设备长宽', windowWidth, windowHeight)
          image.src = path // bgggggg
          image.onload = () => {
            context.drawImage(image,0,0,width,height, 0, 0, windowWidth, windowHeight-108) // 【背景绘制】        
              // 生成员工照片
              const imageWorker = node.createImage()
              imageWorker.src = this.data.workerLogo 
              imageWorker.onload = ()=>{
                let nodeWidth = node.width
                let widthVolume = 0.08 // 人像长宽调节系数
                let heightVolume = 0.09 // 人像长宽调节系数
                let picVolume = 1 // 人像缩放系数
                let typeWidthV = 1 // type字体宽调节
                let typeHeightV = 5 // type字体纵向距离调节(画布Y轴初始坐标)
                let workerHeightV = 0.09 // worker字体高度调节
                let workerWidthV = 0 // worker字体横向距离调节(画布Y轴初始坐标,同上)
                switch(true){
                  case windowWidth==414:
                    console.log('414 机型##########################')
                    picVolume = 1.1
                    widthVolume = 0.07
                    heightVolume = 0.11
                    workerHeightV = 0.41
                    workerWidthV = 10
                    typeWidthV = 0.95
                    typeHeightV = 16
                    break;
                  case windowWidth==375:
                    console.log('#### 375 机型 ##############')
                    picVolume = 1
                    widthVolume = 0.05
                    heightVolume = 0.07
                    workerHeightV = 0.27
                    workerWidthV = 0
                    typeWidthV = 0.78
                    typeHeightV = 18
                    break;
                  case windowWidth==390 || windowWidth==392 :
                      console.log('#### 390 392 机型 ##############')
                      picVolume = 1.1
                      widthVolume = 0.045
                      heightVolume = 0.065
                      workerHeightV = 0.27
                      workerWidthV = data.worker.length>3?  -1 : 6
                      typeWidthV = 1
                      typeHeightV = 20
                      break;
                    case windowWidth==393:
                        console.log('#### 393 机型 ##############')
                        picVolume = 1.1
                        widthVolume = 0.045
                        heightVolume = 0.065
                        workerHeightV = 0.29
                        workerWidthV = data.worker.length>3?  -1 : 6
                        typeWidthV = 1
                        typeHeightV = 20
                        break;
                  case windowWidth==428 || windowWidth==429 || windowWidth==430:
                        console.log('#### 428 428 机型 ##############')
                        picVolume = 1.2
                        widthVolume = 0.045
                        heightVolume = 0.065
                        workerHeightV = 0.27
                        workerWidthV = data.worker.length>3?  11 : 16
                        typeWidthV = 1.1
                        typeHeightV = 2
                        break;
                  case windowWidth>=360&&windowWidth<370: // 小屏机型测试
                      console.log('#### 360 360 机型 ##############')
                      widthVolume = 0.05
                      heightVolume = 0.059
                      workerHeightV = 0.26
                      typeWidthV = 0.79
                      workerWidthV = -1
                      picVolume = 0.9
                      typeHeightV = 22
                      break;     
                  case nodeWidth>=770 && nodeWidth<850:
                        picVolume = 0.7
                        widthVolume = 0.08
                        heightVolume = 0.1   
                        workerHeightV = 0.33
                        typeWidthV = 0.76
                        workerWidthV = 0
                        typeHeightV = 22
                        break;               
                  case nodeWidth>=850&&nodeWidth<1150:
                     widthVolume = 0.08
                     heightVolume = 0.1   
                     workerHeightV = 0.35
                     typeWidthV = 0.8
                     workerWidthV = 10
                     break;         
                  case nodeWidth>=1150&&nodeWidth<1270:
                    widthVolume = 0.05
                    heightVolume = 0.06
                    picVolume = 0.9
                    typeWidthV = 0.79
                    workerHeightV = 0.22
                    break;         
                  case nodeWidth>=1270:
                    console.log('AAAAAAAAAAAAA进来了吗')
                      widthVolume = 0.068
                      heightVolume = 0.06
                      picVolume = 0.9
                      typeWidthV = 0.79
                      workerHeightV =  0.23
                      break;         
                }
                context.drawImage(imageWorker,0,0,2478,3096, node.width*widthVolume, node.height*heightVolume, 272.58*picVolume, 340.56*picVolume) // 【员工头像生成绘制】
                    /* 设置字体样式 大小 字体类别 */
                context.font = 'normal 500 39px PingFangSC-Regular',
                // console.log('字体距离', node.width, workerHeightV, node.height*workerHeightV)
                context.fillText(`${data.worker} `, 5+workerWidthV, node.height*workerHeightV )     // 【工程师信息绘制】
                context.font = 'normal 500 24px PingFangSC-Regular',
                context.fillText(`${data.type}`, (110 + node.width*widthVolume)*typeWidthV,  windowHeight-208+typeHeightV)
                // node.height = windowHeight-108
                const image2 = node.createImage()
                console.log('生成的qrcode',this.data.qrcode_image)
                image2.src = this.data.qrcode_image // 二维码qrcode
                image2.onload = () => {
                  context.arc(windowWidth-53, windowHeight-163, 48, 0, Math.PI * 2, false); // 画圆
                  context.clip();//画好了圆 剪切这个区域 限制画布在一个圆内
                  context.drawImage(image2,0,0,430,430, windowWidth-100,windowHeight-210,94,92)  // 【二维码绘制】
                  this.saveHiaboLocal(node, context, node) // 大坑，必须传入node变量，不能是页面dom节点
                }
              }
            
            // }
          }
        } )

        // qrcode_image
      })
  }, // PIC保存为临时路径，传到父组件生成本地保存处理
  saveHiaboLocal(value, ctx, node){
    console.log('saveHiaboLocal')
    setTimeout(()=>{
      wx.canvasToTempFilePath({
        canvas: value,
        success:  (res) =>{
          console.log('saveHiaboLocal success')
          let tempFilePath = res.tempFilePath;
          this.setData({
            canvasImage: tempFilePath
          },()=>{
            this.setData({ showCreateBtn: false, inCanvasLoading: false})
            // ctx.clearRect(0,0, node.width, node.height)
            this.triggerEvent('onSaveLocal', this.data.canvasImage)
            return  });  },
        fail: function (res) { console.log(res);  }
      });
    }, 0)
  },
  async create_qrcode_image(data) {
    console.log('生成的worker', data)
    let callcloud = await wx.cloud.callFunction({
      name:'qrcode',   // 云函数生成小程序码
      data:{
        worker: data.worker, //data.worker 周纪峰
        uuid: data.uuid // data.uuid zhoujifeng-总部中-装维工程师
      } })
    console.log('QrCode回调 ', callcloud)
    return callcloud.result
  }
    }
})
